package com.acegear.horizon.domain.models;

import com.acegear.horizon.ApplicationContextProvider;
import com.acegear.horizon.domain.models.jpa.AGDaily;
import com.acegear.horizon.domain.models.jpa.AGDailyFeed;
import com.acegear.horizon.domain.models.vo.*;
import com.acegear.horizon.domain.repository.jpa.AGDailyFeedRepository;
import com.acegear.horizon.domain.repository.jpa.AGDailyRepository;

import java.util.Comparator;
import java.util.stream.Collectors;

/**
 * Created by wangsike on 2016/12/22.
 */
public class Daily {

    private AGDaily agDaily;

    private AGDailyFeedRepository agDailyFeedRepository;

    private AGDailyRepository agDailyRepository;

    public Daily(AGDaily agDaily) {
        this.agDaily = agDaily;
        init();
    }

    private void init() {
        agDailyFeedRepository =
                ApplicationContextProvider.getBean(AGDailyFeedRepository.class);

        agDailyRepository =
                ApplicationContextProvider.getBean(AGDailyRepository.class);
    }

    public AGDaily getAgDaily() {
        return agDaily;
    }

    public void setAgDaily(AGDaily agDaily) {
        this.agDaily = agDaily;
    }

    public AGDaily getDaily() {
        agDaily.getFeeds().sort(Comparator.comparingInt(AGDailyFeed::getPosition));

        return agDaily;
    }

    public void update(Daily other) {
        agDaily.update(other.getAgDaily());
        save();
    }

    public void save() {
        agDailyRepository.save(agDaily);
    }

    public DailyDetailVO getDailyDetailVO(Long viewerId) {
        return new DailyDetailVO(
                agDaily.getDailyId(),
                agDaily.getDate(),
                agDaily.getBackground(),
                agDaily.getFeeds()
                        .stream()
                        .map(feed -> getFeedVO(feed, viewerId))
                        .filter(this::filterPost)
                        .collect(Collectors.toList())
        );
    }

    private DailyFeedVO getFeedVO(AGDailyFeed feed, Long viewerId) {
        switch (feed.getFeedType()) {
            case POST:
                return new DailyPostVO(viewerId, feed.getFeedId());
            case EVENT:
                return new DailyEventVO(viewerId, feed.getFeedId());
            case VOTE:
                return null;
            default:
                return null;
        }
    }

    private boolean filterPost(DailyFeedVO feed) {
        if (feed.getBody() == null) {
            return false;
        }
        return true;
    }

    public DailyVO getDailyVO() {
        return new DailyVO(getAgDaily());
    }
}
